<template>
  <my-dialog :show="visible" ref="myDialog">
    <div slot="title" class="dialog-title-row">
      <span class="dialog-title">点数风暴 - 单局详情</span>
      <div class="dialog-tools">
        <el-button
          size="mini"
          type="primary"
          :loading="isRefreshing"
          :disabled="isRefreshing"
          @click="fetchDetailList"
        >
          刷新明细
        </el-button>
        <div class="auto-refresh-switch">
          <span class="switch-label">自动刷新</span>
          <el-switch
            v-model="autoRefreshEnabled"
            active-text="开"
            inactive-text="关"
          />
        </div>
      </div>
    </div>

    <div class="sum-info">
      <div class="sum-item">
        <div class="label">一共投掷次数</div>
        <div class="value">{{ detailPointInfo.size || 0 }}</div>
      </div>
      <div class="sum-item">
        <div class="label">总消费金额</div>
        <div class="value">{{ detailPointInfo.money || 0 }}</div>
      </div>
    </div>

    <my-table style="height: auto">
      <el-table
        :data="detailData"
        style="width: 100%"
        header-row-class-name="table-header"
        v-loading="isRefreshing"
      >
        <el-table-column type="index" label="排名" width="80" align="center" header-align="center" />
        <el-table-column label="玩家" min-width="160" header-align="center">
          <template slot-scope="scope">
            <div class="player-info">
              <img
                width="22"
                height="22"
                :src="scope.row.avator || scope.row.avatar || defaultAvatar"
                @error="onAvatarError($event)"
              />
              <span class="text">{{ scope.row.wx_name || scope.row.nickname || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="投掷次数" min-width="120" align="center" header-align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.hby_size || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最高点数" min-width="120" align="center" header-align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.c02 || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" min-width="100" align="center" header-align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.gsum || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间" min-width="160" align="center" header-align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.create_time">{{ new Date(scope.row.create_time) | formatDate }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
    </my-table>

    <div class="pageNation-container">
      <el-pagination
        background
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalResult"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <div style="text-align: right; padding: 10px 0 20px 0">
      <el-button @click="$emit('update:visible', false)">关闭</el-button>
    </div>
  </my-dialog>
</template>

<script>
import MyTable from '@/components/myTable';
import myDialog from '@/components/myDialog';
import { getPointInfo } from '@/api/setting/activityIncome/activityIncomeData';
import { formatDate as formatDateUtil } from '@/utils/format';

export default {
  name: 'StormDetailDialog',
  components: { MyTable, myDialog },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    liveId: {
      type: String,
      default: '',
    },
    diceId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      detailData: [],
      detailPointInfo: {},
      totalResult: 0,
      currentPage: 1,
      pageSize: 10,
      isRefreshing: false,
      autoRefreshEnabled: false,
      autoRefreshTimer: null,
      defaultAvatar: require('@/assets/image/icon/userCenter/defaultAvatar.png'),
      wrapperClickHandler: null,
    };
  },
  mounted() {
    // 监听 el-dialog 的关闭事件
    this.$nextTick(() => {
      if (this.$refs.myDialog && this.$refs.myDialog.$el) {
        const elDialogWrapper = this.$refs.myDialog.$el.querySelector('.el-dialog__wrapper');
        if (elDialogWrapper) {
          // 监听 el-dialog 的 close 事件
          const elDialog = elDialogWrapper.querySelector('.el-dialog');
          if (elDialog) {
            // 通过监听父元素的点击事件来检测关闭
            const handleWrapperClick = (e) => {
              if (e.target === elDialogWrapper && this.visible) {
                this.$emit('update:visible', false);
              }
            };
            elDialogWrapper.addEventListener('click', handleWrapperClick);
            this.wrapperClickHandler = handleWrapperClick;
          }
        }
      }
    });
  },
  watch: {
    visible(val) {
      if (val) {
        this.currentPage = 1;
        this.fetchDetailList();
        if (this.autoRefreshEnabled) {
          this.startAutoRefresh();
        }
      } else {
        this.stopAutoRefresh();
      }
    },
    autoRefreshEnabled(val) {
      if (val && this.visible) {
        this.startAutoRefresh();
      } else {
        this.stopAutoRefresh();
      }
    },
  },
  methods: {
    fetchDetailList() {
      if (this.isRefreshing) return;

      this.isRefreshing = true;
      const params = {
        splid: this.liveId,
        dice_id: this.diceId,
        currentPage: `${this.currentPage}`,
        showCount: `${this.pageSize}`,
      };

      getPointInfo(params)
        .then((res) => {
          const data = res.data || {};
          this.detailData = data.list || [];
          this.totalResult = data.totalResult || 0;
          this.detailPointInfo = data.pointInfo || {};
        })
        .catch(() => {
          this.detailData = [];
          this.totalResult = 0;
        })
        .finally(() => {
          this.isRefreshing = false;
        });
    },

    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchDetailList();
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchDetailList();
    },

    startAutoRefresh() {
      if (this.autoRefreshTimer) return;
      this.autoRefreshTimer = setInterval(() => {
        if (this.visible && !this.isRefreshing) {
          this.fetchDetailList();
        }
      }, 5000);
    },

    stopAutoRefresh() {
      if (this.autoRefreshTimer) {
        clearInterval(this.autoRefreshTimer);
        this.autoRefreshTimer = null;
      }
    },

    onAvatarError(e) {
      e.target.src = this.defaultAvatar;
    },

    formatTime(time) {
      return formatDateUtil(time, 'yyyy/MM/dd hh:mm:ss');
    },
  },
  filters: {
    // 时间戳
    formatDate(time) {
      if (!time) return '-';
      const date = time instanceof Date ? time : new Date(time);
      return formatDateUtil(date, 'yyyy/MM/dd hh:mm:ss');
    },
  },
  beforeDestroy() {
    this.stopAutoRefresh();
    if (this.wrapperClickHandler && this.$refs.myDialog && this.$refs.myDialog.$el) {
      const elDialogWrapper = this.$refs.myDialog.$el.querySelector('.el-dialog__wrapper');
      if (elDialogWrapper) {
        elDialogWrapper.removeEventListener('click', this.wrapperClickHandler);
      }
    }
  },
};
</script>

<style lang="less" scoped>
.dialog-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.dialog-title {
  font-size: 18px;
  font-weight: 600;
}
.dialog-tools {
  display: flex;
  align-items: center;
  gap: 12px;
}
.auto-refresh-switch {
  display: flex;
  align-items: center;
  gap: 8px;
}
.switch-label {
  font-size: 14px;
  color: #606266;
}
.sum-info {
  display: flex;
  gap: 24px;
  padding: 10px 0;
}
.sum-item {
  display: flex;
  flex-direction: column;
  .label {
    font-size: 12px;
    color: #666666;
  }
  .value {
    font-size: 18px;
    color: #fb466c;
  }
}
.player-info {
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    border-radius: 50%;
    margin-right: 5px;
  }
  .text {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.pageNation-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}
</style>
